<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="100x"
    >
      <el-form-item label="生产单号" prop="no">
        <el-input
            v-model="queryParams.no"
            placeholder="请输入生产计划单编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="生产状态" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择生产状态"
            clearable
            class="!w-240px"
        >
          <el-option label="未审批" value="10"/>
          <el-option label="加工中" value="20"/>
          <el-option label="已完工" value="30"/>
        </el-select>
      </el-form-item>
      <el-form-item label="产品" prop="productId">
        <ErpSelectRemoteProduct v-model="queryParams.productId" @select="selectProduct" class="!w-240px"/>

      </el-form-item>
      <el-form-item label="计划完工" prop="planFinishTime">
        <el-date-picker
            v-model="queryParams.planFinishTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="实际完工" prop="realFinishTime">
        <el-date-picker
            v-model="queryParams.realFinishTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="销售订单号" prop="salesOrderNo">
        <el-input
            v-model="queryParams.salesOrderNo"
            placeholder="请输入销售订单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>

        <el-form-item label="机器" prop="machineId">
          <ErpSelectMachine v-model="queryParams.machineId"   class="!w-240px"/>
        </el-form-item>



        <el-form-item label="模具" prop="mouldId">
          <ErpSelectMould v-model="queryParams.mouldId"   class="!w-240px"/>
        </el-form-item>



        <el-form-item label="生产人" prop="produceUserId">
          <cascader-user v-model="queryParams.produceUserId"   class="!w-240px"/>
        </el-form-item>



      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['erp:produce-plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['erp:produce-plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
        <!--        <el-button-->
        <!--            type="danger"-->
        <!--            plain-->
        <!--            :disabled="isEmpty(checkedIds)"-->
        <!--            @click="handleDeleteBatch"-->
        <!--            v-hasPermi="['erp:produce-plan:delete']"-->
        <!--        >-->
        <!--          <Icon icon="ep:delete" class="mr-5px"/>-->
        <!--          批量删除-->
        <!--        </el-button>-->

        <el-button
            plain
            type="success"
            :disabled="isEmpty(checkedIds)"
            @click="handleSetStatusBatch(20)"
            v-hasPermi="['erp:produce-plan:admin']"
        >
          <Icon icon="ep:check" class="mr-5px"/>
          审批
        </el-button>
        <el-button
            plain
            type="danger"
            :disabled="isEmpty(checkedIds)"
            @click="handleSetStatusBatch(10)"
            v-hasPermi="['erp:produce-plan:admin']"
        >
          <Icon icon="ep:remove" class="mr-5px"/>
          反审批
        </el-button>
        <el-button
          plain
          type="warning"
          :disabled="isEmpty(checkedIds)"
          @click="handleRemachine(30)"
          v-hasPermi="['erp:produce-plan:admin']"
        >
          <Icon icon="ep:refresh" class="mr-5px"/>
          重新加工
        </el-button>
        <el-button
          plain
          type="primary"
          :disabled="checkedIds.length < 2"
          @click="handleMergeOrders"
          v-hasPermi="['erp:produce-plan:admin']"
        >
          <Icon icon="ep:connection" class="mr-5px"/>
          合并订单
        </el-button>

      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="30"/>
      <el-table-column label="状态" align="center" prop="status" width="90" fixed="left">
        <template #default="scope">
          <el-tag v-if="scope.row.status=='10'" type="danger">未审批</el-tag>
          <el-tag v-if="scope.row.status=='20'" type="success">加工中</el-tag>
          <el-tag v-if="scope.row.status=='30'">已完工</el-tag>

        </template>
      </el-table-column>
      <el-table-column label="生产单号" align="center" prop="no" width="180"/>
      <el-table-column label="销售订单号" align="center" prop="salesOrderNo" width="180"/>
      <el-table-column label="产品名称" align="center" prop="productId_dictText" width="100"/>
<!--      <el-table-column label="产品单位" align="center" prop="productUnitId_dictText"/>-->
      <el-table-column label="订购数量" align="center" prop="orderCount"/>
      <el-table-column label="生产数量" align="center" prop="produceCount"/>
      <el-table-column label="入库数量" align="center" prop="inCount"/>
      <el-table-column
          label="计划完工日期"
          align="center"
          prop="planFinishTime"
          :formatter="dateFormatter2"
          width="120px"
      />
      <el-table-column
          label="实际完工日期"
          align="center"
          prop="realFinishTime"
          :formatter="dateFormatter2"
          width="120px"
      />

<!--      <el-table-column label="验收数量" align="center" prop="checkCount"/>-->


      <el-table-column label="备注" align="center" prop="remark"  width="120px"/>
      <el-table-column label="机器" align="center" prop="machineId_dictText"/>
      <el-table-column label="模具" align="center" prop="mouldId_dictText"/>
      <el-table-column label="生产人" align="center" prop="produceUserName"/>
      <el-table-column label="创建人" align="center" prop="creator_dictText"/>
      <el-table-column
          label="单据日期"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />
      <el-table-column label="操作" align="center" min-width="160px" fixed="right">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openDetails('process', scope.row)"
              v-if="scope.row.status==20"
              v-hasPermi="['erp:produce-plan:admin']"
          >
            加工
          </el-button>

          <el-button
              link
              type="primary"
              @click="openDetails('view', scope.row)"
              v-else
              v-hasPermi="['erp:produce-plan:admin']"
          >
            查看
          </el-button>
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row)"
              v-hasPermi="['erp:produce-plan:update']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row)"
              v-hasPermi="['erp:produce-plan:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProducePlanForm ref="formRef" @success="getList"/>
  <ProductPlanDetails ref="detailsRef" @success="getList"/>
</template>

<script setup lang="ts">
import {isEmpty} from '@/utils/is'
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import {ProducePlan, ProducePlanApi} from '@/api/erp/produce/plan'
import ProducePlanForm from './ProducePlanForm.vue'
import ProductPlanDetails from './ProducePlanDetails.vue'
import ErpSelectRemoteProduct from "@/views/erp/product/product/components/ErpSelectRemoteProduct.vue";
import ErpSelectMachine from "@/views/erp/basic/machine/components/ErpSelectMachine.vue";
import ErpSelectMould from "@/views/erp/basic/mould/components/ErpSelectMould.vue";

/** ERP 生产计划单 列表 */
defineOptions({name: 'ErpProducePlan'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProducePlan[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  status: undefined,
  productId: undefined,
  salesOrderNo: undefined,
  planFinishTime: [],
  realFinishTime: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProducePlanApi.getProducePlanPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  if (type == "update" && row.status != 10) {
    message.error("抱歉，该状态下不能编辑！")
    return
  }

  formRef.value.open(type, row?.id)
}
const detailsRef = ref()

const openDetails = (type: string, row?: any) => {
  if(type=='view'&&row.status==10){
    message.error("抱歉，该状态下不能查看！")
    return
  }
  detailsRef.value.open(type, row.id)
}


/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    if (row.status != 10) {
      message.error("抱歉，只有未审批的单据才能删除!")
      return
    }
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProducePlanApi.deleteProducePlan(row.id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 批量删除ERP 生产计划单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ProducePlanApi.deleteProducePlanList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {
  }
}

const handleSetStatusBatch = async (status: number) => {
  try {
    // 删除的二次确认
    await message.confirm("是否操作选中数据?", "确认操作-" + (status == 20 ? "审批" : "反审"))
    await ProducePlanApi.updateSaleOrderStatus(checkedIds.value.join(','), status);
    checkedIds.value = [];
    message.success("操作成功")
    await getList();
  } catch {
  }
}

const handleRemachine = async () => {
  try {
    // 删除的二次确认
    await message.confirm("是否操作选中数据?", "确认操作-重新加工")
    await ProducePlanApi.remachine(checkedIds.value.join(','));
    checkedIds.value = [];
    message.success("操作成功")
    await getList();
  } catch {
  }
}

/** 合并订单操作 */
const handleMergeOrders = async () => {
  try {
    // 验证:至少需要2个订单
    if (checkedIds.value.length < 2) {
      message.error("请至少选择2个订单进行合并")
      return
    }

    // 获取选中的订单记录
    const selectedOrders = list.value.filter(item => checkedIds.value.includes(item.id!))

    // 验证:所有订单状态必须是未审核(10)
    const hasNonPendingOrder = selectedOrders.some(order => order.status != '10')
    if (hasNonPendingOrder) {
      message.error("只能合并未审核状态的订单")
      return
    }

    // 验证:所有订单的产品必须相同
    const firstProductId = selectedOrders[0].productId
    const hasDifferentProduct = selectedOrders.some(order => order.productId !== firstProductId)
    if (hasDifferentProduct) {
      message.error("只能合并相同产品的订单")
      return
    }

    // 显示确认信息
    const orderNos = selectedOrders.map(order => order.no).join('、')
    const totalCount = selectedOrders.reduce((sum, order) => sum + (order.orderCount || 0), 0)
    const productName = selectedOrders[0].productId_dictText || '未知产品'
    await message.confirm(
      `确认合并以下订单?\n订单号: ${orderNos}\n产品: ${productName}\n合并后数量: ${totalCount}`,
      "确认合并订单"
    )

    // 调用后端API进行合并
    await ProducePlanApi.mergeOrders(checkedIds.value)
    checkedIds.value = []
    message.success("订单合并成功")
    await getList()
  } catch {
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ProducePlan[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProducePlanApi.exportProducePlan(queryParams)
    download.excel(data, 'ERP 生产计划单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
